package com.chengyi.serialport.demo.printer

import com.chengyi.serialboard.sdk.Openable
import com.chengyi.serialboard.sdk.SerialPortOptions
import com.hjq.toast.Toaster
import com.print.usbprint.command.Label
import tp.xmaihh.serialport.SerialHelper
import tp.xmaihh.serialport.bean.ComBean
import tp.xmaihh.serialport.stick.BaseStickPackageHelper
import tp.xmaihh.serialport.utils.ByteUtil
import java.io.Closeable
import java.util.Vector

class JpwPrinterSerialPortUtil(private val options: SerialPortOptions, private var callback: Callback?) : Openable, Closeable {

    interface Callback {
        fun onSendCallback(hex: String)
        fun onReceiverCallback(hex: String)
    }

    private val serialPortHelper = object : SerialHelper(options.path, options.baudrate) {
        override fun onDataReceived(paramComBean: ComBean?) {
            val data = paramComBean?.bRec ?: return
            callback?.onReceiverCallback(ByteUtil.ByteArrToHex(data))
        }
    }.also {
        it.stickPackageHelper = BaseStickPackageHelper()
    }

    override fun open(): Boolean {
        if (serialPortHelper.isOpen) {
            return true
        }
        return try {
            serialPortHelper.open()
            true
        } catch (e: Exception) {
            Toaster.show("串口${options.path} ${options.baudrate}打开失败")
            false
        }
    }

    override fun close() {
        serialPortHelper.close()
        callback = null
    }

    override val isOpen: Boolean
        get() = serialPortHelper.isOpen

    fun doPrint(label: Label) {
        val data = convertVectorByteToBytes(label.command)
        callback?.onSendCallback(ByteUtil.ByteArrToHex(data))
        serialPortHelper.send(data)
    }


    private fun convertVectorByteToBytes(data: Vector<Byte>): ByteArray {
        val sendData = ByteArray(data.size)
        if (data.size > 0) {
            for (i in data.indices) {
                sendData[i] = data[i] as Byte
            }
        }
        return sendData
    }
}